package com.example.personnel_management_system.controller;

import com.example.personnel_management_system.controller.ex.*;
import com.example.personnel_management_system.entity.Roles;
import com.example.personnel_management_system.service.IRolesService;
import com.example.personnel_management_system.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("roles")
public class RolesController extends BaseController{
    public static Integer MAX_IMG_SIZE=10*1024*1024;
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();
    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }
    @Autowired
    private IRolesService rolesService;
    @RequestMapping("/getType")
    public Result<String> getType(HttpServletRequest request){
        Roles roles=rolesService.findByrID((Integer)request.getSession().getAttribute("UId"));
        if(roles==null)
            return Result.failure();
        return Result.success(roles.getrType());
    }
    @RequestMapping("/getRoles")
    public Result<Roles>getRoles(HttpServletRequest request){
        Roles roles=rolesService.findByrID((Integer)request.getSession().getAttribute("UId"));
        if(roles==null)
            return Result.failure();
        return Result.success(roles);
    }
    @RequestMapping("/findall")
    public Result<List<Roles>> findall(){
        return Result.success(rolesService.findall());
    }
    @RequestMapping("/updateRoles")
    public Result<Void>updateRoles(Roles target,HttpServletRequest request){
        Roles roles=rolesService.findByrID((Integer)request.getSession().getAttribute("UId"));
        if(roles==null)
            return Result.failure();
        target.setrID(roles.getrID());
        target.setrType(roles.getrType());
        try {
            rolesService.update(target);
        }catch (Exception e){
            return Result.failure();
        }
        return Result.success();
    }
    @RequestMapping("/updateType")
    public Result<Void>updateType(Roles target){
        Roles roles=rolesService.findByrID(target.getrID());
        if(roles==null)
            return Result.failure();
        roles.setrType(target.getrType());
        try {
            rolesService.update(roles);
        }catch (Exception e){
            return Result.failure();
        }
        return Result.success();
    }
    @RequestMapping("updateRolesImg")
    public Result<String>updateRolesImg(@RequestParam("myfile") MultipartFile multipartFile, HttpSession session){
        System.out.println("上传开始");
        if (multipartFile.isEmpty()) {
            // 是：抛出异常
            throw new FileEmptyException("上传的头像文件不允许为空");
        }

        // 判断上传的文件大小是否超出限制值
        if (multipartFile.getSize() > MAX_IMG_SIZE) {
            // 是：抛出异常
            throw new FileSizeException("不允许上传超过" + (MAX_IMG_SIZE / 1024) + "KB的头像文件");
        }
        String contentType = multipartFile.getContentType();
        if (!AVATAR_TYPES.contains(contentType)) {
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：" + AVATAR_TYPES);
        }

        String parent=session.getServletContext().getRealPath("upload");
        System.out.println("文件路径"+parent);
        File dir=new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String suffix = "";
        String originalFilename = multipartFile.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }
        String filename = UUID.randomUUID().toString() + suffix;

        File dest = new File(dir, filename);
        try {
            multipartFile.transferTo(dest);
        } catch (IllegalStateException e) {
            // 抛出异常
            throw new FileStateException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            // 抛出异常
            throw new FileUploadIOException("上传文件时读写错误，请稍后重新尝试");
        }
        String imgurl = "/upload/" + filename;

        Integer uId = (Integer)session.getAttribute("UId");
        Roles roles=rolesService.findByrID(uId);
        roles.setrImgurl(imgurl);
        rolesService.update(roles);
        // 返回成功头像路径
        return Result.success(imgurl);
    }
}
